package main

import (
	"bytes"
	"crypto/sha1"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
)

func shaAndDel(src string, sha []byte) []byte {

	h := sha1.New()

	dest, err := os.OpenFile(src, os.O_RDONLY, 0666)
	if err != nil {
		fmt.Println(err)
		return nil
	}

	t := io.TeeReader(dest, h)

	ioutil.ReadAll(t)
	if err != nil {
		fmt.Println(err)
		return nil
	}

	sha1 := h.Sum(nil)
	// fmt.Printf("sha:%x\n", sha1)
	dest.Close()
	if bytes.Equal(sha, sha1) {
		fmt.Println("delete:" + src)
		err := os.Remove(src)
		if err != nil {
			fmt.Println(err)
		}

	}

	return sha1
}
func walkfunc(path string, f os.FileInfo, err error) error {
	if f == nil {
		return err
	}
	if f.IsDir() {
		return nil
	}
	shaAndDel(path, hashBytes)
	return nil

}

var hashBytes []byte

func main() {
	// fn := flag.String("", "", "input filename") // echo -n flag, of type *bool

	flag.PrintDefaults()
	flag.Parse() // Scans the arg list and sets up flags
	fn := flag.Arg(0)
	if fn == "" {
		fmt.Println("file is nil")
		return
	} else {
		fmt.Println("dir:" + filepath.Dir(fn))
	}
	hashBytes = shaAndDel(fn, nil)
	fmt.Printf("sha:%x\n ", hashBytes)
	filepath.Walk(filepath.Dir(fn), walkfunc)

}
